package com.wlf.admin.common.freemarker;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.wlf.admin.common.config.SysConfig;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateHashModel;
import lombok.extern.slf4j.Slf4j;


/**
 * 功能描述: FreeMarker全局属性注入
 *
 * @author wlf 2023/8/16 14:28
 */
@Slf4j
public class FreemarkerConfig {

    public static void init() {

        Configuration c = SpringUtil.getBean(Configuration.class);
        BeansWrapperBuilder beansWrapperBuilder = new BeansWrapperBuilder(c.getIncompatibleImprovements());
        BeansWrapper wrapper = beansWrapperBuilder.build();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        try {
            TemplateHashModel dateUtil = (TemplateHashModel) staticModels.get(DateUtil.class.getName());
            TemplateHashModel stpUtil = (TemplateHashModel) staticModels.get(StpUtil.class.getName());
            c.setSharedVariable("dateUtil", dateUtil);
            c.setSharedVariable("stpUtil", stpUtil);
            c.setSharedVariable("sysConfig", SpringUtil.getBean(SysConfig.class));
            c.setSharedVariable("hasPerm", SpringUtil.getBean(HasPerm.class));
            // 默认输出,如果无小数点即是整数，有 小数点则显示小数点。
            c.setNumberFormat("#.########");
            // 定义数字格式，在页面中使用   <#setting number_format="#"> 标签来指定数字格式化
            // 或者这种写法，写法  ${x?string.@amt}可指定此格式输出，
            c.setCustomNumberFormats(MapUtil.of("amt", AmtTemplateNumberFormatFactory.INSTANCE));
            c.setDateTimeFormat(DatePattern.NORM_DATETIME_PATTERN);
            c.setDateFormat(DatePattern.NORM_DATE_PATTERN);
            c.setTimeFormat(DatePattern.NORM_TIME_PATTERN);
            c.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        } catch (Exception e) {
            log.error("FreeMarker全局变量注入失败!", e);
        }
    }
}
